package com.example.springboot.mapper;

import com.example.springboot.entity.CollectIncorrectQuestion;
import com.example.springboot.entity.vo.IncorrectQuestionVo;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface CollectIncorrectQuestionMapper {


    Integer  insertCollectIncorrectQuestion(CollectIncorrectQuestion collectIncorrectQuestion);


    @Select("SELECT * FROM collect_incorrect_question WHERE id = #{id}")
    CollectIncorrectQuestion getCollectById(Integer id);

    @Delete("DELETE FROM collect_incorrect_question WHERE id = #{id}")
    void deleteCollect(Integer id);
    @Delete("DELETE FROM collect_incorrect_question WHERE incorrect_question_id = #{questionId}")
    void deleteCollectByIncorrectQuestionId(Integer questionId);

    @Select("""
        SELECT COUNT(1) > 0
        FROM collect_incorrect_question
        WHERE user_id = #{userId} AND incorrect_question_id = #{incorrectQuestionId}
    """)
    boolean isIncorrectQuestionCollected(
            @Param("userId") Integer userId,
            @Param("incorrectQuestionId") Integer incorrectQuestionId
    );

    @Select("""
        SELECT 
            iq.id AS id,
            ciq.user_id AS userId,
            iq.question_id AS questionId,
            q.post_id AS postId,
            q.question AS question,
            q.options AS options,
            q.correct_answer AS correctAnswer,
            q.created_at AS questCreatedAt,
            q.updated_at AS questUpdatedAt,
            ciq.created_at AS createdAt,
            ciq.updated_at AS updatedAt
        FROM 
            collect_incorrect_question ciq
        JOIN 
            incorrect_questions iq 
        ON 
            ciq.incorrect_question_id = iq.id
        JOIN 
            questions q 
        ON 
            iq.question_id = q.id
        WHERE 
            ciq.user_id = #{userId}
        ORDER BY 
            ciq.created_at DESC
        LIMIT #{pageSize} OFFSET #{pageNum}
    """)
    List<IncorrectQuestionVo> getCollectsByUserId(
            @Param("userId") Integer userId,
            @Param("pageNum") Integer pageNum,
            @Param("pageSize") Integer pageSize
    );

    @Select("SELECT id FROM collect_incorrect_question WHERE user_id = #{userId} AND incorrect_question_id = #{incorrectQuestionId} LIMIT 1")
    Integer getCollectIdByUserIdAndIncorrectQuestionId(@Param("userId") Integer userId, @Param("incorrectQuestionId") Integer incorrectQuestionId);

}
